package cn.houserent.web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.houserent.entity.House;
import cn.houserent.entity.PageSupport;
import cn.houserent.service.HouseBiz;
import cn.houserent.service.impl.HouseBizImpl;

public class HouseServlet extends HttpServlet {
	
	private HouseBiz houseService = new HouseBizImpl();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		House house = new House();
		house.setTitle(request.getParameter("title"));
		Double price = null;
		if(request.getParameter("price") != null && request.getParameter("price") != ""){
			price = Double.parseDouble(request.getParameter("price"));
			house.setPrice(price);
		}
		DateFormat fmt =new	SimpleDateFormat("yyyy-MM-dd");
		Date pubdate = null;
		try {
			if(request.getParameter("pubdate") != null && request.getParameter("pubdate") != ""){
				pubdate = fmt.parse(request.getParameter("pubdate"));
				house.setPubdate(pubdate);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(request.getParameter("contact") != null && request.getParameter("contact") != ""){
			house.setContact(request.getParameter("contact"));
		}
		PageSupport page = new PageSupport();
		page.setPageSize(5);
		page.setTotalCount(houseService.getCount(house));
		if(request.getParameter("pageIndex") != null && request.getParameter("pageIndex") != ""){
			Integer pageIndx = Integer.parseInt(request.getParameter("pageIndex"));
			page.setCurrentPageNo(pageIndx);
		}
		List<House> houseList = houseService.getHouseList(house, (page.getCurrentPageNo()-1)*page.getPageSize(), page.getPageSize());
		request.getSession().setAttribute("houseList", houseList);
		request.setAttribute("page",page);
		request.getRequestDispatcher("list.jsp").forward(request,response);
	}

}
